package com.ljpz.manage.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.abel533.entity.Example;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljpz.common.bean.EasyUIResult;
import com.ljpz.common.bean.ItemCatResult;
import com.ljpz.common.service.ApiService;
import com.ljpz.manage.mapper.ItemMapper;
import com.ljpz.manage.pojo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liujunchen on 2016/11/29.
 */
@Service
public class ItemService  extends  BaseService<Item>{
    @Autowired
    private ItemMapper  itemMapper  ;
    @Autowired
        private  ItemDescService itemDescService ;
    @Autowired
    private ItemParamItemService  itemParamItemService   ;
    @Autowired
    private ApiService apiService  ;
    @Value("${LJPZ_WEB_URL}")
    private  String  LJPZ_WEB_URL  ;
    @Autowired
    private RabbitTemplate rabbitTemplate  ;
    private static    final ObjectMapper MAPPER=  new ObjectMapper()   ;
    public  boolean   saveItem(Item item ,String desc,String itemParams){
        //初始值
        item.setStatus(1);
        item.setId(null);//出于安全考虑， 强制设置id 为null ， 通过数据库自增长得到对应的
        Integer   count1   =  super.save(item)  ;
        ItemDesc itemDesc  = new ItemDesc();
        itemDesc.setitemId(item.getId());
        itemDesc.setItemDesc(desc );
        Integer  count2  = this.itemDescService.save(itemDesc )  ;
        //保存规格参数数据
        ItemParamItem  itemParamItem    = new ItemParamItem() ;
        itemParamItem.setItemId(item.getId());
        itemParamItem.setParamData(itemParams);
        Integer  count3= this.itemParamItemService.save(itemParamItem)   ;
        //发送消息到MQ的交换机，并且通知其他的系统
        sendMsg(item.getId(),"insert");
        return   count1.intValue()==1  &&count2.intValue()==1 &&count3.intValue()==1  ;

    }

    public EasyUIResult queryItemList(Integer page, Integer rows) {
        // 设置分页参数
        PageHelper.startPage(page,rows);
        Example example = new Example(Item.class)  ;
        example.setOrderByClause("created desc");
        List<Item>  items = itemMapper.selectByExample(example);
        //获取分页后的的的信息
        PageInfo<Item>pageinfo =  new PageInfo<Item>(items)  ;
        return   new EasyUIResult(pageinfo.getTotal(), pageinfo.getList())   ;
    }

    public Boolean updateItem(Item item, String desc,String  itemParams ) {
        item.setStatus(null);  // 强制设置状态不能被修改
        Integer count1  = super.updateSelective(item )  ;
        ItemDesc itemDesc   =   new ItemDesc()  ;
        itemDesc.setitemId(item.getId());
        itemDesc.setItemDesc(desc );
        Integer  count2  = this.itemDescService.updateSelective(itemDesc)  ;
        //更新规格参数数据
        Integer count3  = this.itemParamItemService.updateItemParamItem(item.getId() , itemParams) ;
        //通知其他系统该商品已经更新（不能影响自己的业务逻辑）
        //主动去通知前台系统item已经更新
        /*try {
            String url= LJPZ_WEB_URL +"/item/cache/"+item.getId()+".html" ;
            this.apiService.doPost(url) ;
        } catch (Exception  e) {
            e.printStackTrace();
        }*/

       //把消息对应放在统一消息队列中去
       sendMsg(item.getId(),"update");
        return     count1.intValue()==1 &&count2.intValue()==1;
    }

    /**
     * 调用rabbitMQ把更改通知写到队列中去
     * @param itemId
     * @param type
     */
    private   void  sendMsg(Long itemId, String type ){
        try {
            //发送消息到MQ的交换机器，通知其他系统已经变更
            Map<String,Object>  msg=  new HashMap<String,Object>()  ;
            msg.put("itemId" , itemId) ;
            msg.put("type",type);
            msg.put("date", System.currentTimeMillis()) ;
            //发送到消息队列中去

            //this.rabbitTemplate.convertAndSend("item."+type, MAPPER.writeValueAsString(msg));
            this.rabbitTemplate.convertAndSend("item."+type,MAPPER.writeValueAsString(msg));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

}
